// JavaScript Document

var themes = {

	ajax_page: "ajax_pages/themes.php",

	init: function() {

		$p(".theme-name-link").bind("click", themes.themeNameAction );
		
		// chrome and firefox throw errors by not returning a usable HTMLElement
		// opera and IE9+ will execute following without error
		try {
			$p(".theme-name-link").node(0).click(); //.fire('click');
		} catch(e) {}
		
		$p("#theme-install-link").bind('click', function() {
			$p.post('forms/theme_upload_form.php', "", function(data) {
				$p.showDialog({
					title: 'Installing New Theme',
					content: data,
					okButtonText: "Upload And Install",
					okButtonAction: function() {
						$p.postMultiPartForm( themes.ajax_page, "#theme_upload_form", null, function(data) {							
							if( $p.trim(data) != "" ) {
								alert(data);
							} else {
								history.go(0);
							}
                            
                            $p.hideDialog();
						});
                        
                        return false;
					}
				});
			});
		});
        
        $p("#theme-duplicate-link").bind('click',function() {
            var id = $p(this).attr("data-id");
            
            $p.confirm("This action will duplicate this theme info and its files. Do you want to continue?", function() {
                var query = "action=duplicate&theme_id=" + id;
                
                $p.post( themes.ajax_page, query, function(data) {
                     var obj = $p.parseJSON(data);
                     
                     if( obj ) {
                         
                         var a = $p.create("a").addClass("theme-name-link").attr("data-id", obj.id).attr("href","#")
                                .attr("title", "Preview Theme On Right").html( "&nbsp;" + ($p(".row-checker").count() + 1) + ". " + obj.ThemeName)
                                .bind('click', themes.themeNameAction).node(0);
                         
                         var input = $p.create("input").attr("type","checkbox").attr("name","row-check")
                                        .attr("class","row-checker").val( obj.id ).node(0);
                         
                         var div = $p.create("div").attr("id","row-" + obj.id).addClass("row").node(0);
                         
                         div.appendChild(input);
                         div.appendChild(a);
                         
                         document.getElementById("theme-rows").appendChild(div);
                     }
                });
            });
        });
		
		$p("#theme-edit-link").bind('click',function() {
			var id = $p(this).attr("data-id");
			
			var query = "action=edit_theme&theme_id=" + id;
			$p.post( themes.ajax_page, query, function(data) {
				$p.showDialog({
					title: "Edit Theme",
					content: data,
					okButtonText: "Save Changes",
					okButtonAction: function() {
						themes.updateTheme();
					}
				}, function() {
					ui.htmlMiniEditor("ThemeDesc");	
				});	
			});
		});

		$p("#theme-export-link").bind('click',function(){
			var href = "ajax_pages/themes.php?action=export_theme&theme_id=" + $p(this).attr("data-id");
			window.location.href = href;
		});
		
		$p("#theme-delete-link").bind('click',function() {
			var id = $p(this).attr("data-id");
			
			$p.confirm("Do you want to delete this theme?", function() {
				var query = "action=delete_theme&theme_id=" + id;	
				$p.post( themes.ajax_page, query, function() {
					$p("#row-" + id).remove();
				});
			});
		});
		
		$p("#all-checker").bind('click',function() {
			var checked = this.checked;
			$p.all(".row-checker",function(el){
				el.checked = checked;
			});
		});
		
		$p("#add-link").bind('click',function() {
			$p.post('forms/theme_create_form.php', "", function(data) {
				$p.showDialog({
					title: 'Create New Theme',
					content: data,
					okButtonText: 'Create New Theme',
					okButtonAction: function() {
						return themes.createTheme();
					}
				});
				
				ui.htmlMiniEditor("ThemeDesc");
			});	
		});
		
		$p("#delete-link").bind('click',function(){
			$p.confirm("Do you want to delete the selected theme(s)?",function() {
				var selected = [];
				$p.all(".row-checker:checked",function(el) {
					selected.push( el.value );
				});
				
				var query = "action=delete_themes&ids=" + selected;
				$p.post( themes.ajax_page, query, function(data) {
					for(var i = 0; i < selected.length; i++) {
						$p("#row-" + selected[i]).remove();	
					}
				});
			});	
		});
		
		$p('#theme-create-form #ThemeFolder').bind('keyup', function() {
			var folderPath = this.value;
			var folderName = folderPath.split("/")[3];
			
			if( folderName != "<folder-name>" ){
				$p("#root-folder-text").html(folderName);
			}
		});
		
		// prevent the theme-create-form from submitting when the button is clicked
		$p('#create-theme-btn').bind('click', function() {
			
			if( !$p("#theme-create-form").validate() ) {
				return;
			}
			
			if( $p('#ThemeFolder').val() == "../assets/themes/<folder-name>/" ) {
				$p.inform("Please Edit The Folder Name Value To Use To Create The Theme Folder");
				return;
			}
			
			$p("#theme-create-form").node(0).submit();
		});
		
		if( document.getElementById("ThemeDesc") ) {
			ui.htmlMiniEditor("ThemeDesc");
			
			ui.htmlMiniEditor("CSSDescription");
		}
	},
    
    themeNameAction: function() {
        var id = $p(this).attr("data-id");
        var query = "action=load_info&theme_id=" + id;

        $p(".split_view .row").removeClass("selected");
        $p(".split_view #row-" + id).addClass("selected");
        $p(".nav .nav-link").attr("data-id", id);

        $p.post( themes.ajax_page, query, function(data) {
            $p("#info_view").html(data);
            file_utils.attachFolderHandlers();
        });
    },
	
	createTheme: function() {
		var valid = $p("#create-theme-form").validate();
		
		if( !valid ) {
			return false;	
		}	
		
		if( $p('#ThemeFolder').val() == "../assets/themes/<folder-name>/" ) {
			alert("Please Edit The Folder Name Value To Use To Create The Theme Folder");
			return false;
		}
		
		// save the contents of the description field
		tinyMCE.triggerSave();
		
		var query = "action=create_theme&" + $p("#create-theme-form").serialize();
		$p.post( themes.ajax_page, query, function(data) {
			if( $p.trim(data) != "" ) {
				$p.inform(data);
			} else {
				window.history.go(0);
			}
		});
		
		return true;
	},
	
	updateTheme: function() {
		var valid = $p("#update-theme-form").validate();
		
		if( !valid ) {
			return false;	
		}	
		
		if( $p('#ThemeFolder').val() == "../assets/themes/<folder-name>/" ) {
			alert("Please Edit The Folder Name Value To Use To Create The Theme Folder");
			return false;
		}
		
		// save the contents of the description field
		try {
			tinyMCE.triggerSave();
		} catch(e) {};
		
		var query = "action=update_theme&" + $p("#update-theme-form").serialize();
		$p.post( themes.ajax_page, query, function(data) {
			if( $p.trim(data) != "" ) {
				$p.inform(data);
			} else {
				window.history.go(0);
			}
		});
		
		return true;
	}
};

function initEditorContent() {
	var hf = document.getElementById("CSSContent");
	document.getElementById("editorApplet").setEditorContent( hf.value );
}

function showAppletEditor() {
	
	var fields = document.getElementById("cssedit_form").getElementsByTagName("input");
	for(var i = 0; i < fields.length; i++) {
		fields.item(i).disabled = true;	
	}
	
	pageManager.show('editor_area');
}

function saveAppletEditorContent() {
	var field = document.getElementById("CSSContent");
	field.value = document.getElementById("editorApplet").getEditorContent();
	pageManager.hide('editor_area');	
	
	var fields = document.getElementById("cssedit_form").getElementsByTagName("input");
	for(var i = 0; i < fields.length; i++) {
		fields.item(i).disabled = false;	
	}
}
